package com.example.finger.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.finger.FingerHelper;
import com.example.finger.bean.KeyValue;
import com.example.finger.R;
import com.example.finger.adpter.AddTaskAdapter;
import com.example.finger.bean.Task;
import com.example.finger.bean.TaskSheet;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyxmaster.lib.circledialog.CircleDialog;
import com.lyxmaster.lib.circledialog.callback.ConfigInput;
import com.lyxmaster.lib.circledialog.params.InputParams;
import com.lyxmaster.lib.circledialog.view.listener.OnInputClickListener;
import com.lyxmaster.lib.customdatepicker.CustomDatePicker;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.SharedPreferencesHelper;
import com.lyxmaster.lib.view.BackActivity;
import com.lyxmaster.lib.xutils.view.annotation.ContentView;
import com.lyxmaster.lib.xutils.view.annotation.ViewInject;
import com.lyxmaster.lib.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LYX on 2018/11/27.
 * 添加任务页面
 */
@ContentView(R.layout.activity_add_task)
public class AddTaskActivity extends BackActivity {
    @ViewInject(R.id.listview)
    private ListView listView;

    private List<KeyValue> list = new ArrayList<>();
    private AddTaskAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        setTitle("添加临时任务单");

        for(String temp : getResources().getStringArray(R.array.SETTING)){
            KeyValue keyValue = new KeyValue();
            keyValue.setKey(temp);
            keyValue.setValue("");
            list.add(keyValue);
        }
        TypedArray arr = getResources().obtainTypedArray(R.array.SETTINGDRAW);
        for (int i=0; i<arr.length(); i++){
            list.get(i).setDrawable(arr.getResourceId(i, 0));
        }
        adapter = new AddTaskAdapter(list, context);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                switch (position)
                {
                    case 0:
                    case 1:
                        selectTime(position);
                        break;
                    case 2:
                    case 3:
                    case 5:
                        inputData(position);
                        break;
                    case 4:
                        List<String> listTemp = new ArrayList<>();
                        if(!TextUtils.isEmpty(list.get(position).getValue())){
                            String[] nums = list.get(position).getValue().split(" ");
                            for (int i=0; i<nums.length; i++){
                                listTemp.add(nums[i]);
                            }
                        }
                        Intent intent = new Intent(context, AddLockActivity.class);
                        intent.putExtra("data", new Gson().toJson(listTemp));
                        startActivityForResult(intent, 0);
                        break;
                }
            }
        });
    }

    private void selectTime(final int position){
        CustomDatePicker customDatePicker = new CustomDatePicker(context, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                Toasty.success(context, time).show();
                list.get(position).setValue(time);
                adapter.notifyDataSetChanged();
            }
        }); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(true);
        customDatePicker.setIsLoop(false); // 不允许循环滚动
        customDatePicker.setTitle(list.get(position).getKey());
        customDatePicker.show();
    }

    /**
     * 输入数据
     */
    private void inputData(final int position) {
        new CircleDialog.Builder()
                .setCanceledOnTouchOutside(true)
                .setCancelable(true)
                .setTitle(list.get(position).getKey())
                .configInput(new ConfigInput() {
                    @Override
                    public void onConfig(InputParams params) {
                        params.gravity = Gravity.CENTER;
                        params.text = list.get(position).getValue();
                    }
                })
                .setNegative("取消", null)
                .setPositiveInput("确定", new OnInputClickListener() {
                    @Override
                    public void onClick(String text, View v) {
                        list.get(position).setValue(text);
                        adapter.notifyDataSetChanged();
                    }
                })
                .showWithkeyboard(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.positive_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //当用户点击Action按钮的时候，系统会调用Activity的onOptionsItemSelected()方法
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_add:
                save();
                return true;
            case android.R.id.home:
                exit();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
        switch (requestCode) {
            case 0:
                List<String> listTemp = new Gson().fromJson(data.getStringExtra("data"), new TypeToken<List<String>>() {
                }.getType());
                String nums = "";
                for (int i = 0; i < listTemp.size(); i++) {
                    nums += listTemp.get(i) + " ";
                }
                nums = nums.trim();
                list.get(4).setValue(nums);
                adapter.notifyDataSetChanged();
                break;
        }
    }

    private void save(){
        Intent intent = new Intent();
        setResult(Activity.RESULT_OK, intent);

        for(KeyValue keyvalue : list){
            if(TextUtils.isEmpty(keyvalue.getValue())){
                Toasty.error(context,"请将内容补充完整").show();
                return;
            }
        }

        Task task = new Task();
        task.setNumber((new Date().getTime() + "").substring(0, 10));
//        task.setTimeStatust(list.get(0).getValue());
        task.setTimeend(list.get(1).getValue());
        task.setOp1(list.get(2).getValue());
        task.setOp2(list.get(3).getValue());
        task.setLocknum(list.get(4).getValue());
        task.setRemark(list.get(5).getValue());
        TaskSheet taskSheet = new TaskSheet();
        ArrayList<Task> tasks = new ArrayList<>();
        tasks.add(task);
        taskSheet.setTask(tasks);
        FingerHelper.getInStance().taskSheetTempList.add(taskSheet);
        new SharedPreferencesHelper().putSharedPreference(context,FingerHelper.TMEMPTASK, new Gson().toJson(FingerHelper.getInStance().taskSheetTempList));

        finish();
    }

    private void exit(){
        boolean bEdit = false;
        for(KeyValue keyvalue : list){
            if(!TextUtils.isEmpty(keyvalue.getValue())){
                bEdit = true;
            }
        }
        if(bEdit){
            new CircleDialog.Builder(AddTaskActivity.this)
                    .setCanceledOnTouchOutside(true)
                    .setCancelable(true)
                    .setTitle("退出")
                    .setText("添加挂锁未保存，确定要退出吗？")
                    .setNegative("取消", null)
                    .setPositive("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            finish();
                        }
                    }).show();
        }else {
            finish();
        }
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {;
            exit();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
